//src/utils.h
#ifndef UTILS_H
#define UTILS_H

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <errno.h>

// --- 日志宏 ---
#define LOG_LEVEL_INFO  0
#define LOG_LEVEL_ERROR 1
#define CURRENT_LOG_LEVEL LOG_LEVEL_INFO

#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)

#define LOG(level, format, ...) do { \
    if (level >= CURRENT_LOG_LEVEL) { \
        time_t timer; \
        char time_buf[26]; \
        struct tm* tm_info; \
        time(&timer); \
        tm_info = localtime(&timer); \
        strftime(time_buf, 26, "%Y-%m-%d %H:%M:%S", tm_info); \
        fprintf(stdout, "[%s] [%s] [%s:%d] " format "\n", \
                time_buf, (level == LOG_LEVEL_INFO ? "信息" : "错误"), \
                __FILENAME__, __LINE__, ##__VA_ARGS__); \
        if (level == LOG_LEVEL_ERROR && errno != 0) { \
            fprintf(stdout, "        系统错误: %s\n", strerror(errno)); \
        } \
    } \
} while (0)

#define LOG_INFO(format, ...) LOG(LOG_LEVEL_INFO, format, ##__VA_ARGS__)
#define LOG_ERROR(format, ...) LOG(LOG_LEVEL_ERROR, format, ##__VA_ARGS__)

// --- 常量定义 (根据编译选项切换) ---
#define CHUNK_SIZE 4096

// 如果定义了 USE_XXHASH, 则使用 xxHash
#ifdef USE_XXHASH
    #define CHUNK_HASH_LEN 16
    #define CHUNK_HASH_FUNC calculate_xxh64_hex
    #define CHUNK_HASH_NAME "xxHash64"
#else // 否则, 默认使用 SHA256
    #define CHUNK_HASH_LEN 64
    #define CHUNK_HASH_FUNC calculate_sha256_hex
    #define CHUNK_HASH_NAME "SHA256"
#endif

// 为了兼容 oci_builder.c 中对 sha256 的硬编码
#define SHA256_HEX_LEN 64
// 同样定义一下 xxhash 的长度, 避免 utils.c 编译出错
#define XXH64_HEX_LEN 16

// --- 函数声明 ---
int calculate_sha256_hex(const unsigned char* data, size_t size, char* output);
int calculate_xxh64_hex(const unsigned char* data, size_t size, char* output);
int run_command(const char* format, ...);

#endif // UTILS_H